﻿using System;
using System.Collections.Generic;
using System.Text;
using ServiceHelper;
using Components;
using System.Collections;
using System.Data;
using ControlService.DataModel;
using Model;
using System.ServiceModel;
using ReturnPageData = ControlService.DataModel.ReturnPageData;


namespace ControlService
{
    [ServiceBehavior(UseSynchronizationContext = false)]//同步异步区别于此，经测试异步可极大提高服务效率
    public class CommonContract : ICommonContract
    {
        public string GetAuthKey()
        {
            if (OperationContext.Current != null)
            {
                return OperationContext.Current.IncomingMessageHeaders.GetHeader<string>("AuthKey", Globals.ProductUrl);
            }

            return null;
        }

        #region 系统相关

        /// <summary>
        /// 根据页面和控件名称得到页面字段信息
        /// </summary>
        /// <param name="page">页面名称</param>
        /// <param name="ctl">控件名称</param>
        /// <returns></returns>
        public System.Data.DataTable GetColumnByPageAndCtl(string page, string ctl, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            return Sys5a01Manager.Entity.GetList(Context.Decrypt(guid, page), Context.Decrypt(guid, ctl));
        }

        public string GetColumnByPageAndCtls(string page, string ctls, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            page = Context.Decrypt(guid, page);
            ctls = Context.Decrypt(guid, ctls);

            List<string> list = Json.ToObject<List<string>>(ctls);
            Dictionary<string, string> ret = new Dictionary<string, string>();

            foreach (var ctl in list)
            {
                var data = Sys5a01Manager.Entity.GetList(page, ctl);
                if (ret.ContainsKey(ctl) == false)
                {
                    var str = Json.ToString(data);
                    ret.Add(ctl, str);
                }
            }

            string json = Json.ToString(ret);

            return StringUtil.Zip(json);
        }

        /// <summary>
        /// 得到Session列表
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="guid"></param>
        /// <param name="isLogin"></param>
        /// <returns></returns>
        public DataTable GetSession(BLLService.Pager pager, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            Model.Pager page = new Model.Pager();
            CommonUtil.GetInstance.CopyProperties(pager, page, true, true);

            return Context.GetSessionList();
        }

        /// <summary>
        /// 得到Main页面分页数据
        /// </summary>
        /// <param name="pager"></param>
        /// <returns></returns>
        public ReturnPageData GetPageList(BLLService.Pager pager, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            Model.Pager page = new Model.Pager();
            CommonUtil.GetInstance.CopyProperties(pager, page, true, true);

            page.AutoWhere = string.IsNullOrEmpty(page.AutoWhere) ? " 1 = 1" : page.AutoWhere;
            page.StrWhere = string.IsNullOrEmpty(page.StrWhere) ? page.AutoWhere : page.StrWhere + " AND " + page.AutoWhere;
            //为当前的数据自动加上公司的限制条件
            if (!string.IsNullOrEmpty(page.FilterAppName))
            {
                page.StrWhere += Context.BuildAppWhere(page.FilterAppName, guid, !string.IsNullOrEmpty(page.StrWhere));
            }

            var model = new ReturnPageData(CommonManager.Entity.GetDefaultRecordCount(page));

            model.TableToData(CommonManager.Entity.GetPageData(page));

            model.TableToSummary(CommonManager.Entity.GetSummery(page));

            return model;
        }

        /// <summary>
        /// 根据页面和控件得到页面控件实体
        /// </summary>
        /// <param name="page"></param>
        /// <param name="ctl"></param>
        /// <returns></returns>
        public String GetSys5a00(string page, string ctl, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            string value =
                StringUtil.Entity.DeserializeObject(
                    Sys5a00Manager.Entity.GetModel(Context.Decrypt(guid, page), Context.Decrypt(guid, ctl))
                );

            return StringUtil.Zip(value);
        }

        /// <summary>
        /// 公用的保存方法
        /// </summary>
        /// <param name="callFun">保存时候调用的业务逻辑层的方法</param>
        /// <param name="data">Json字符串</param>
        /// <returns></returns>
        public string Save(string callFun, string data, string action, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            string[] funs = Context.Decrypt(guid, callFun).Split('$'); //分割方法
            if (funs.Length < 2) return "回写的方法名称错误！";
            Hashtable ht = StringUtil.Entity.JsonToTable(Context.Decrypt(guid, data), true);

            try
            {
                //被反射的类必须是只有一个字符串参数，且返回一个字符串
                object refStr = CommonUtil.GetInstance.GetInfoByReflect("ServiceHelper",
                                                            funs[0],
                                                            funs[1],
                                                            new object[]
                                                                {
                                                                    ht, Context.Decrypt(guid, action),
                                                                    Context.GetUserCode(guid)
                                                                });

                return null == refStr ? "" : refStr.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Entity.Out(ex);
                return ex.Message;
            }
        }

        /// <summary>
        /// 公用的保存方法
        /// </summary>
        /// <param name="callFun">保存时候调用的业务逻辑层的方法</param>
        /// <param name="data">Json字符串</param>
        /// <returns></returns>
        public string SaveDtl(string callFun, string data, string action, DataTable dtldata, DataTable deldata, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            string[] funs = Context.Decrypt(guid, callFun).Split('$'); //分割方法
            if (funs.Length < 2) return "回写的方法名称错误！";
            Hashtable ht = StringUtil.Entity.JsonToTable(Context.Decrypt(guid, data), true);

            try
            {
                //被反射的类必须是只有一个字符串参数，且返回一个字符串
                object refStr = CommonUtil.GetInstance.GetInfoByReflect("ServiceHelper", funs[0], funs[1], new object[] { ht, dtldata, deldata, Context.Decrypt(guid, action), Context.GetUserCode(guid) });

                return null == refStr ? "" : refStr.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Entity.Out(ex);
                return ex.Message;
            }
        }

        public DataTable[] GetTables(string callFun, string where, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            string[] funs = Context.Decrypt(guid, callFun).Split('$'); //分割方法
            if (funs.Length < 2) return null;
            Hashtable ht = StringUtil.Entity.JsonToTable(Context.Decrypt(guid, where), true);
            //被反射的类必须是只有一个字符串参数，且返回一个字符串
            object refObj = CommonUtil.GetInstance.GetInfoByReflect("ServiceHelper", funs[0], funs[1], new object[] { ht, Context.GetUserCode(guid) });

            return refObj == null ? null : (DataTable[])refObj;
        }

        /// <summary>
        /// 根据数据库设置的数据源，加载数据
        /// </summary>
        public System.Data.DataTable LoadEditData(string page, string action, string ctl, string where, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            return CommonManager.Entity.GetSys5a02Data(
                        Context.Decrypt(guid, page),
                        Context.Decrypt(guid, action),
                        Context.Decrypt(guid, ctl),
                        Context.Decrypt(guid, where)
                );
        }

        /// <summary>
        /// 得到权限列表
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public string GetPermision(string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            DataTable data = Sys0a05Manager.Entity.GetCurrentUserPermission(Context.GetUserCode(guid));

            return Json.ToStringZip(data);
        }

        /// <summary>
        /// 得到POPWIN弹出数据
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="fields"></param>
        /// <param name="otherFieldName"></param>
        /// <param name="order"></param>
        /// <param name="where"></param>
        /// <param name="otherWhere"></param>
        /// <param name="rownum"></param>
        /// <returns></returns>
        public string GetPopData(string tableName, string fields, string otherFieldName, string order, string where, string otherWhere, int rownum, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            DataTable data = PopManager.GetInitialize.GetPopData(
                        Context.Decrypt(guid, tableName),
                        Context.Decrypt(guid, fields),
                        Context.Decrypt(guid, otherFieldName),
                        Context.Decrypt(guid, order),
                        Context.Decrypt(guid, where),
                        Context.Decrypt(guid, otherWhere),
                rownum);

            return Json.ToStringZip(data);
        }

        public ControlService.DataModel.PopItem GetPopItem(string popno, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            Model.PopItem pop = PopManager.GetInitialize.GetPopItem(Context.Decrypt(guid, popno));
            if (null == pop) return null;
            DataModel.PopItem refModel = new ControlService.DataModel.PopItem();
            CommonUtil.GetInstance.CopyProperties(pop, refModel, true, true);

            return refModel;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public string Login(String userName, String pwd, string mac, bool mk)
        {
            return Sys0a00Manager.Entity.CheckLogin(userName, pwd, mac, mk);
        }

        /// <summary>
        /// 得到版本列表
        /// </summary>
        /// <returns></returns>
        public string GetVesionList()
        {
            return CommonUtil.GetInstance.LoadFromFile("updatecfg.xml");
        }

        /// <summary>
        /// 下线
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public string LoginOut(string guid)
        {
            return Context.RemoveGuid(guid);
        }

        /// <summary>
        /// 检查数据库中的数据是否存在
        /// </summary>
        /// <param name="tbName"></param>
        /// <param name="where"></param>
        /// <param name="guid"></param>
        /// <param name="isLogin"></param>
        /// <returns></returns>
        public bool DataInDb(string tbName, string where, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return false; //检测用户失败，返回
            }

            return CommonManager.Entity.HasData(
                    Context.Decrypt(guid, tbName),
                    Context.Decrypt(guid, where)
                );
        }

        /// <summary>
        /// 执行数据库的函数
        /// </summary>
        /// <param name="key"></param>
        /// <param name="where"></param>
        /// <param name="guid"></param>
        /// <param name="isLogin"></param>
        /// <returns></returns>
        public string ExecFun(string key, string where, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            DataTable data = CommonManager.Entity.ExecDBFun(key, where);

            string stream = Json.TableToXml(data);
            return StringUtil.Zip(stream);
        }

        public string ExecFunScalar(string key, string where, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            object o = CommonManager.Entity.ExecDbFunScalar(key, where);

            return Validation.ToString(o);
        }

        /// <summary>
        /// 得到权限列表
        /// </summary>
        /// <param name="modulecode"></param>
        /// <param name="guid"></param>
        /// <param name="isLogin"></param>
        /// <returns></returns>
        public string GetActionList(string modulecode, string guid, ref bool isLogin)
        {
            isLogin = true;
            if (!Context.CheckUser(guid))
            {
                isLogin = false;
                return null; //检测用户失败，返回
            }

            return Sys0a05Manager.Entity.GetModulePermission(modulecode, guid);
        }

        public string Exchange(string key)
        {
            if (null == key) return "E1|未知序号！";
            MacKey mkey = new MacKey(key);
            //保存下值
            Context.AddMac(mkey);
            SecurityEncryption.key = mkey.Mac.Substring(0, 8);

            return SecurityEncryption.Encrypt(mkey.Key);
        }
        #endregion
    }
}
